<template>
  <n-card title="摄像头管理" :bordered="false">
    <template #header-extra>
      <n-button type="primary" @click="openCreateModal">
        <template #icon>
          <n-icon><PlusOutlined /></n-icon>
        </template>
        添加摄像头
      </n-button>
    </template>
    <n-layout has-sider  style="height: calc(100vh - 80px)">
      <!-- 左侧分组管理 -->
      <DeviceGroup />

      <!-- 右侧设备清单 -->
      <n-layout>
        <n-space vertical>
          <!-- 新增操作按钮和搜索框 -->
          <n-space justify="space-between" align="center">
            <n-space>
              <n-button
                type="primary"
                @click="fetchData"
                :disabled="!selectedRowKeys.length"
              >
                <template #icon>
                  <n-icon><RefreshOutlined /></n-icon>
                </template>
                刷新
              </n-button>
              <n-button
                type="info"
                @click="handleBatchCapture"
                :disabled="!selectedRowKeys.length || isBatchCapturing"
              >
                <template #icon>
                  <n-icon><CameraOutlined /></n-icon>
                </template>
                抓图{{ isBatchCapturing ? `(${captureProgress}%)` : '' }}
              </n-button>
              <n-button type="success" @click="handleImport" >
                <template #icon>
                  <n-icon><UploadOutlined /></n-icon>
                </template>
                导入
              </n-button>
              <n-button
                type="warning"
                @click="handleExport"
                :disabled="!selectedRowKeys.length"
              >
                <template #icon>
                  <n-icon><DownloadOutlined /></n-icon>
                </template>
                导出
              </n-button>
              <n-button
                type="error"
                @click="handleBatchDelete"
                :disabled="!selectedRowKeys.length"
              >
                <template #icon>
                  <n-icon><DeleteOutlined /></n-icon>
                </template>
                删除
              </n-button>
            </n-space>
            <n-input
              v-model:value="searchValue"
              placeholder="搜索设备"
              clearable
              style="width: 300px"
            />
          </n-space>
          <n-data-table
            :columns="columns"
            :data="deviceList"
            :pagination="pagination"
            :loading="loading"
            :scroll-x="1200"
            style="height: calc(100% - 60px)"
            :row-key="row => row.id"
            :single-column="true"
            :checked-row-keys="selectedRowKeys"
            @update:checked-row-keys="handleCheckedRowKeysChange"
            @update:page="handlePageChange"
            @update:page-size="handlePageSizeChange"
          />
        </n-space>
      </n-layout>
    </n-layout>

  </n-card>

  <n-modal v-model:show="showAddModal">
    <n-card style="width: 600px" title="添加摄像头" :bordered="false">
      <CreateDevice ref="createDeviceRef" @success="handleAddSuccess" />
    </n-card>
  </n-modal>

  <n-modal v-model:show="showImageModal">
    <n-card style="width: 80vw; max-width: 1200px" :bordered="false">
      <img :src="currentImageUrl" style="width: 100%; height: auto"  alt=""/>
    </n-card>
  </n-modal>

  <PlayVideo
    v-if="showLiveStreamModal"
    :key="currentStreamUrl"
    :url="currentStreamUrl"
    :show="showLiveStreamModal"
    @close="showLiveStreamModal = false"
  />
</template>

<script lang="ts" setup>
import {h, nextTick, onMounted, reactive, ref,} from 'vue';
import {
  CameraOutlined,
  DeleteOutlined,
  DownloadOutlined,
  FolderOutlined,
  PlusOutlined,
  UploadOutlined
} from '@vicons/antd';
import {NButton, NDataTable, NLayout, NSpace, useMessage} from 'naive-ui';
import {renderIcon} from "@/utils";
import {
  DeleteDevice,
  Device,
  FetchDeviceList,
  FetchGroupList,
  GetDevice,
  RtspCapture,
  RtspConvertHls,
} from '@/api/analysis/device';

import CreateDevice from './CreateDevice.vue';
import DeviceGroup from './DeviceGroup.vue';
import PlayVideo from './PlayVideo.vue';

const showLiveStreamModal = ref(false);
const currentStreamUrl = ref('');

const selectedRowKeys = ref([]);

const message = useMessage();
const loading = ref(false);

const filteredGroupOptions = ref<any[]>([]);
const defaultExpandedKeys = ref<string[]>([]);

const searchValue = ref('');
const deviceList = ref<ReadonlyArray<Device>>([]);

const createDeviceRef = ref<InstanceType<typeof CreateDevice> | null>(null);

function handlePageChange(page: number) {
  pagination.page = page;
  fetchData(); // 重新获取数据
}

const isBatchCapturing = ref(false);
const captureProgress = ref(0);
// 添加分页大小变化处理函数
function handlePageSizeChange(pageSize: number) {
  pagination.pageSize = pageSize;
  fetchData(); // 重新获取数据
}

// 新增操作函数
async function handleBatchCapture() {
  if (selectedRowKeys.value.length === 0) {
    message.warning('请先选择要抓图的设备');
    return;
  }

  try {
    loading.value = true;
    await Promise.all(
      selectedRowKeys.value.map(async (deviceId) => {
        const device = deviceList.value.find(item => item.id === deviceId);

        if (device) {
            const device_id= Number(device?.id) || 0;
            const rtsp_url = device?.rtsp_url || '';
            const imageUrl = await RtspCapture({ device_id:device_id,rtsp_url:rtsp_url });

            // 强制更新预览图URL
            deviceList.value = deviceList.value.map(item =>
              item.id === device.id ? {
                ...item,
                preview_image: `${imageUrl}?t=${Date.now()}` // 添加时间戳避免缓存
              } : item
            );

            return {
              deviceId: device.id,
              deviceName: device.name,
              imageUrl,
              error: null // 明确标记没有错误
            };
        }
        return null;
      })
    );

    await fetchData();
  } catch (error) {
    message.error('批量抓图失败');
    console.error('批量抓图失败:', error);
  } finally {
    loading.value = false;
  }
}

function handleImport() {
  message.info('导入功能待实现');
}

function handleExport() {

  if (selectedRowKeys.value.length === 0) {
    message.warning('请先选择要抓图的设备');
    return;
  }
  // 实现导出逻辑
  message.info(`导出选中设备：${selectedRowKeys.value.join(', ')}`);



}

const checkedRowKeys = ref<number[]>([]);
function handleBatchDelete() {
  if (checkedRowKeys.value.length === 0) {
    message.warning('请先选择要删除的设备');
    return;
  }
  message.info(`删除选中设备：${checkedRowKeys.value.join(', ')}`);
  // 实现批量删除逻辑
  for (const id of checkedRowKeys.value) {
    DeleteDevice(id);
  }
  fetchData()
}




// const playVideoRef = ref<InstanceType<typeof PlayVideo>>();
async function fetchData() {
  loading.value = true;
  try {
    const [deviceListData, groupListData] = await Promise.all([
      FetchDeviceList(),
      FetchGroupList()
    ]);

    deviceList.value = deviceListData.map(item => ({
      id: item.id,
      preview_image: item.preview_image,
      name: item.name,
      status: item.status ? '在线' : '离线',
      rtsp_url: item.rtsp_url,
    }));

    if (createDeviceRef.value) {
      createDeviceRef.value.groupOptions = groupListData.map(group => ({
        label: group.name,
        value: group.id
      }));
    }
  } catch (error) {
    message.error('初始化数据失败');
    console.error("初始化数据失败", error);
  } finally {
    loading.value = false;
  }
}


// 分页配置
const pagination = reactive({
  page: 1,
  pageSize: 10,
  showSizePicker: true,
  pageSizes: [10, 20, 30],
  showQuickJumper: true
});


const showImageModal = ref(false);
const currentImageUrl = ref('');
// 表格列配置
const columns = ref([
  {
    type: 'selection'
  },
  { title: '设备ID', key: 'id' },
  {
    title: '预览图',
    key: 'preview',
    render(row) {
      const previewUrl = row.preview_image || ''; // Add fallback for undefined
      const isLocalhost = previewUrl.includes('localhost')||  previewUrl.includes('127.0.0.1');
      const imgUrl = isLocalhost ? previewUrl : previewUrl + '?x-oss-process=image/resize,w_80';

      return h('img', {
        src: imgUrl,
        style: {
          width: '80px',
          height: 'auto',
          cursor: 'pointer'
        },
        onClick: () => {
          currentImageUrl.value = previewUrl;
          showImageModal.value = true;
        }
      });
    }
  },
  { title: '名称', key: 'name' },
  {
    title: '连接状态',
    key: 'status',
  },
  {
    title: '刷新',
    key: 'refresh',

    render(row) {
      return h(NButton, {
        size: 'small',
        type: 'primary', // 添加type属性
        onClick: () => handleRefresh(row)
      }, '刷新');
    }
  },
  { title: '流地址', key: 'rtsp_url' },
  {
    title: '操作',
    key: 'actions',
    render(row) {
      return h(NSpace, {}, [
        h(NButton, {
          size: 'small',
          onClick: () => handleEdit(row)
        }, '编辑'),
        h(NButton, {
          size: 'small',
          type: 'primary',
          onClick: () => handleLiveStream(row)
        }, '直播流'),
        h(NButton, {
          size: 'small',
          type: 'error',
          onClick: () => handleDelete(row)
        }, '删除')
      ]);
    }
  }
]);

// 操作处理函数
async function handleRefresh(row) {
  try {
    loading.value = true;
    // 获取单个设备最新信息
    const updatedDevice = await GetDevice(row.id);

    // 更新设备列表
    deviceList.value = deviceList.value.map(item =>
      item.id === row.id ? {
        ...item,
        ...updatedDevice,
        preview_image: updatedDevice.preview_image,
        status: updatedDevice.status ? '在线' : '离线'
      } : item
    );

    message.success(`设备 ${row.name} 刷新成功`);
  } catch (error) {
    message.error(`刷新设备 ${row.name} 失败`);
    console.error("刷新设备失败", error);
  } finally {
    loading.value = false;
  }
}

function handleEdit(row) {
  message.success(`编辑设备：${row.name}`);
}

async function handleLiveStream(row) {
  if (!row.rtsp_url || !row.rtsp_url.startsWith('rtsp://')) {
    message.error('无效的流地址');
    return;
  }

  try {
    loading.value = true;
    const hlsUrl = await RtspConvertHls({ url: row.rtsp_url });

    // Validate and assign the converted URL
    if (typeof hlsUrl === 'string' && hlsUrl.trim() !== '') {
      currentStreamUrl.value = hlsUrl;
      showLiveStreamModal.value = true;
    } else {
      throw new Error('Invalid HLS URL returned from server');
    }
  } catch (error) {
    message.error( '播放失败');
    console.error('播放失败:', error);
  } finally {
    loading.value = false;
  }
}

function handleDelete(row) {
  message.success(`删除设备：${row.name}`);
}

// 添加状态和表单数据
const showAddModal = ref(false);

function openCreateModal() {
  showAddModal.value = true;
  nextTick(() => {
    if (createDeviceRef.value) {
      createDeviceRef.value.resetForm();
    }
  });
}

function handleCheckedRowKeysChange(keys) {
  selectedRowKeys.value = keys;
}

function handleAddSuccess() {
  message.success('设备添加成功');
  showAddModal.value = false;
  fetchData(); // 刷新设备列表
}

onMounted(async () => {
  loading.value = true;
  try {
    // 使用 Promise.all 真正并行请求
    const [deviceListData, groupListData] = await Promise.all([
      FetchDeviceList(),
      FetchGroupList()
    ]);

    // 设备数据处理
    deviceList.value = deviceListData.map(item => ({
      id: item.id,
      preview_image: item.preview_image,
      name: item.name,
      status: item.status ? '在线' : '离线',
      rtsp_url: item.rtsp_url,
    }));

    // 分组数据处理
    if (createDeviceRef.value) {
      createDeviceRef.value.groupOptions = groupListData.map(group => ({
        label: group.name,
        value: group.id
      }));
    }

    filteredGroupOptions.value = groupListData.map(group => ({
      label: group.name,
      key: group.id,
      icon: renderIcon(FolderOutlined),
      children: group.children?.map(child => ({
        label: child.name,
        key: child.id,
        icon: renderIcon(FolderOutlined)
      })) || []
    }));

    // 设置默认展开的菜单项（添加空数组检查）
    if (filteredGroupOptions.value.length > 0 && filteredGroupOptions.value[0].key) {
      defaultExpandedKeys.value = [filteredGroupOptions.value[0].key];
    }

  } catch (error) {
    message.error('初始化数据失败');
    console.error("初始化数据失败", error);
  } finally {
    loading.value = false;
  }
});
</script>
